# tdxserver.py
import tdx
import time
import struct
import win32pipe, win32file,pywintypes
import traceback
import threading

PIPE_NAME = r'\\.\pipe\mypipe'
pipe = None
isConnect = 0

def reload_tdx_module():
    import importlib
    importlib.reload(tdx)


def closeserever():
    global pipe
    win32file.CancelIo(pipe)
    win32pipe.DisconnectNamedPipe(pipe)


def cancelIO():
    global pipe
    win32file.CancelIo(pipe)
    win32pipe.DisconnectNamedPipe(pipe)


def pipe_server(on_exit,tlog):
    global pipe,isConnect
    tlog("正在等待客户端连接...")
    isConnect = 1
    # 创建命名管道
    pipe = win32pipe.CreateNamedPipe(
        PIPE_NAME,                      # 管道名称
        win32pipe.PIPE_ACCESS_DUPLEX | win32file.FILE_FLAG_OVERLAPPED ,   # 双向管道
        win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_READMODE_MESSAGE | win32pipe.PIPE_WAIT,
        1,                              # 最大实例数
        65536,                          # 输出缓冲区大小
        65536,                          # 输入缓冲区大小
        0,                              # 默认超时
        None)                           # 默认安全属性

    try:
        # 等待客户端连接
        # tlog(f"pipe{pipe}")
        win32pipe.ConnectNamedPipe(pipe, None)
        tlog("客户端已连接。")
        isConnect = 2
        while True:
            try:
                # 读取客户端数据
                result, data = win32file.ReadFile(pipe, 64 * 1024)
                # 解包数据
                flag,fno,dl = struct.unpack('iii', data[:12])  # 读取 flag
                # tlog(f"flag:{flag}  fno:{fno}  dl:{dl} DataLen:{len(data)}")
                if flag == 2:
                    #只调用函数
                    re = tdx.tdxFuncA(fno,dl)
                    # 打包并返回处理后的结果
                    response = struct.pack(f'{dl}f',*re)
                    win32file.WriteFile(pipe, response)
                elif flag>2:
                    break;
                else:
                    array1 = struct.unpack(f'{dl}f', data[12:12 + dl * 4])  # 读取第一个 float 数组
                    array2 = struct.unpack(f'{dl}f', data[12+dl*4:])   # 读取第二个 float 数组
                    # 处理数据
                    re = tdx.tdxFunc(fno,array1, array2)
                    if (flag==1): 
                        # 打包并返回处理后的结果
                        #tlog(f"result: re[0],re[1],re[2],re[3] ...")
                        response = struct.pack(f'{dl}f',*re)
                        win32file.WriteFile(pipe, response)
            except pywintypes.error as e:
                # tlog(f"123{e}")
                break
            except Exception as e:
                msg = traceback.format_exc()
                tlog(msg)
                break
    except Exception as e:
         pass
        # msg = traceback.format_exc()
        # tlog(msg)
    finally:
        # 关闭管道
        win32file.CloseHandle(pipe)
        isConnect = 0
        on_exit()

